﻿using System;
using System.Collections.Generic;
using VMWorkshop.Domain;
using VMWorkshop.Web.Models;
using AutoMapper;

namespace VMWorkshop.Web.Models.ViewModels
{
    public class WebFormsViewModel
    {
        private IList<ProductListView> _products = null;
        private ProductEditView _selectedProduct = null;
        private IProductRepository _repository = null;
        private bool _isPersistenceSuccessful = false;

        public IList<ProductListView> Products
        {
            get 
            {
                if (this._products == null)
                {
                    var products = this._repository.GetAll();
                    this._products = Mapper.Map<IList<Product>, IList<ProductListView>>(products);
                }
                return this._products;
            }
        }

        public ProductEditView SelectedProduct
        {
            get { return this._selectedProduct; }
        }

        public bool HasSelectedProduct
        {
            get 
            { 
                return !string.IsNullOrEmpty(this._selectedProduct.ProductId); 
            }
        }

        public bool IsPersistenceSuccessful
        {
            get { return this._isPersistenceSuccessful; }
        }

        public WebFormsViewModel(IProductRepository repository)
        {
            this._repository = repository;
            this.ClearSelectedProduct();
        }

        public void GetSelectedProduct(string productId)
        {
            int id;

            if (int.TryParse(productId, out id))
            {
                this.GetSelectedProduct(id);
            }
            else
            {
                throw new ArgumentException("The value for productId must be an integer.");
            }
            
        }
    
        public void GetSelectedProduct(int productId)
        {
            Product product = this._repository.GetProductById(productId);
            this._selectedProduct = ProductEditView.ToProductEditView(product);
        }

        internal void PersistChanges(ProductEditView view)
        {
            Product newProduct = ProductEditView.ToProduct(view);
            Product oldProduct = this._repository.GetProductById(newProduct.ProductId);

            oldProduct = Mapper.Map<Product, Product>(newProduct, oldProduct);

            this._repository.Persist(oldProduct);
            this._isPersistenceSuccessful = true;
            this.ClearSelectedProduct();
        }

        private void ClearSelectedProduct()
        {
            this._selectedProduct = new ProductEditView();
        }
    }
}
